#pragma once

#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>
#include <unistd.h>
#include <vector>

using namespace std;

struct ThreadInfo
{
    pthread_t tid;
    string tname;
};

static const int defalutnum = 5;

template <class T>
class ThreadPool
{
public:
    void lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void threadsleep()
    {
        pthread_cond_wait(&cond_,&mutex_);
    }

    bool IsTasksEmpty()
    {
        return tasks_.empty();
    }
    string GetThreadname(pthread_t id)
    {
        for(auto &ti:threads_)
        {
            if(ti.tid==id)
            {
                return ti.tname;
            }
        }
        return "None";
    }
public:
    ThreadPool(int num = defalutnum)
        : threads_(num)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }

    static void *HandlerTask(void *args)
    {
        ThreadPool<T>*tp=static_cast<ThreadPool<T>*>(args);
        string name=tp->GetThreadname(pthread_self());
        while (1)
        {
            //检测队列有没有任务
            tp->lock();
            while(tp->IsTasksEmpty())
            {
                tp->threadsleep();
            }
            T t=tp->Pop();
            tp->unlock();
            t();//变成了自己的私有数据，就不用在锁里面调用了
            cout<<name<<" run , ret: "<<t.Getret()<<endl;
        }
    }

    void Start()
    {
        int num = threads_.size();
        for (int i = 0; i < num; i++)
        {
            threads_[i].tname = "thread-" + to_string(i + 1);
            pthread_create(&(threads_[i].tid), nullptr, HandlerTask, this);
        }
    }
    T Pop()
    {
        T t=tasks_.front();
        tasks_.pop();
        return t;
    }

    void Push(const T &t)
    {
        lock();
        tasks_.push(t);
        wakeup();
        unlock();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

private:
    vector<ThreadInfo> threads_;
    queue<T> tasks_;

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};
